import {observable, action} from "mobx";
import {Form, ListViewPage, Browser} from "weaver-mobile-page";
import {Tools, Bubble, Modal, Toast} from "weaver-mobile";
import {Base64} from "js-base64";
import ReplyEditorStore from "../reply/replyEditorStore";
import * as API from "../../api";

const getLabel = Tools.getLabel;
export default class taskDetailsStore {
    @observable isLoading = true;
    @observable Toasting = false;
    @observable hasRight = true;
    @observable tabIndex = 0;
    @observable searchValue = "";
    @observable searchValue1 = "";
    @observable currentPage = 1;
    @observable taskid = "1";
    @observable prjid;
    @observable parentid;
    @observable history;
    @observable replyTypes = [];

    @observable rightMenus = {};
    @observable form = new Form.Store();
    @observable ChildTaskList = new ListViewPage.Store({route: "/TaskDetails", id: "1"});

    @observable TaskRelativeReqList = new ListViewPage.Store({route: "/TaskDetails", id: "3"});
    @observable TaskRelativeDocList = new ListViewPage.Store({route: "/TaskDetails", id: "4"});

    @observable browser = new Browser.Store({route: `/TaskDetails/3/${this.taskid}`, id: "search-history"});
    @observable browserValue = [];
    @observable browser2 = new Browser.Store({route: `/TaskDetails/3/${this.taskid}`, id: "search-history"});
    @observable browserValue2 = [];
    @observable comment = new ReplyEditorStore();
    @action
    init = (index, taskid, history, parentid) => {
        this.taskid = taskid;
        this.parentid = parentid;
        this.tabIndex = Number(index);
        this.history = history;
        if (this.tabIndex === 0) {
            this.getForm();
        } else if (this.tabIndex === 1) {
            this.getChildList();
        } else if (this.tabIndex === 2) {
            this.comment = new ReplyEditorStore({
                getComment: this.getReplyDatas,
                source: {taskid: this.taskid},
            });
            this.currentPage = 1;
            this.comment.commentStore.getDatas();
        } else {
            this.getTaskRelativeContent()
        }

    };
    @action
    onTabChange = (index, history) => {
        this.tabIndex = Number(index);
        history.replace("/TaskDetails/" + index + "/" + this.taskid)
    };
    @action
    changeSearchValue = (val) => {
        if (this.tabIndex === 3) {
            this.searchValue = val;
        } else if (this.tabIndex === 4) {
            this.searchValue1 = val;
        }
    };
    @action
    setPage = (p) => {
        this.currentPage = p;
    }
    @action
    getForm = () => {
        this.hasRight = true;
        this.isLoading = true;
        const params = {
            taskid: this.taskid,
            viewtype: "view"
        }
        this.form = new Form.Store();
        API.getTaskForm(params).then(action(res => {
            this.isLoading = false;
            this.hasRight = true;
            const {isright} = res;
            if (isright && isright === true) {
                this.rightMenus = res.rightMenus || {};
                this.prjid = res.prjid;
                this.form.initForm(res.fieldinfo, `/TaskDetails/${this.tabIndex}/${this.taskid}`);
            } else {
                this.hasRight = false;
            }
        }))
    };

    @action
    getChildList = () => {
        this.hasRight = true;
        const params = {
            conditiontype: "sublist",
            taskid: this.taskid
        };
        this.ChildTaskList.clearData();
        API.getTaskList(params).then(action(res => {
            const {isright} = res;
            if (isright && isright === true) {
                this.rightMenus = res.rightMenus || {};
                this.prjid = res.prjid;
                this.ChildTaskList.getData({dataKey: res.datas});
            } else {
                this.hasRight = false;
            }
        }))
    }

    @action
    getReplyDatas = () => {
        this.hasRight = true;
        const params = {
            sortid: this.taskid,
            pageindex: this.currentPage++
        }
        return API.getTaskExchange(params).then(action(res => {
            if (res["isright"] && res["isright"] === true) {
                this.hasRight = true;
                this.rightMenus = res.rightMenus || {};
                this.prjid = res["prjid"];
                this.replyTypes = [].concat(res.replyTypes);
            } else {
                this.hasRight = false;
            }
            const result = res;
            result.replyList.forEach(v => {
                let imgArr = [];
                let content = Base64.decode(v.content);                                 //解码
                let src = content.match(/\bsrc\b\s*=\s*[\'\"]?([^\'\"\s]*)[\'\"]?/ig);  //查找img
                content = content.replace(/<img\b.*?(?:\>|\/>)/gi, "");                 //去除remark 中上传的img（带有fileid字段）
                const aTags = content.match(/<a\b[^>]+\bhref="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi) //搜索所有a标签
                if (aTags) {
                    aTags.forEach(v => {
                        const href = v.match(/<a\b[^>]+\bhref="([^"]*)"[^>]*>([\s\S]*?)<\/a>/)    //查找href和value，并替换href
                        if (href) {
                            content = content.replace(href[1], "javascript:void(0)");
                        }
                    })
                }
                v.content = Base64.encode(content)                                      //编码
                if (src !== null) {
                    src.forEach(v => {
                        const fileid = v.match(/fileid=([a-zA-Z0-9]*)/i)                      //获取fileid
                        if (fileid) {
                            const temp = Array.from(fileid);
                            imgArr.push(temp[1]);                                       //拼接成数组
                        }
                    })
                }
                v.imgArr = imgArr;
            })
            return result
        }))
    }

    @action
    getTaskRelativeContent = () => {
        this.hasRight = true;
        let params = {
            taskid: this.taskid,
        };
        if (this.tabIndex === 3) {
            this.browser = new Browser.Store({route: `/TaskDetails/3/${this.taskid}`, id: "search-history"});
            this.browserValue = [];
            params = {...params, name: this.searchValue, reftype: "req"}
            this.TaskRelativeReqList.clearData();
            API.getTaskReferenceList(params).then(action(res => {
                const {isright} = res;
                if (isright && isright === true) {
                    this.prjid = res["prjid"]
                    this.rightMenus = res.rightMenus || {};
                    this.TaskRelativeReqList.getData({dataKey: res.datas});
                } else {
                    this.hasRight = false
                }
            }))

        } else if (this.tabIndex === 4) {
            this.browser2 = new Browser.Store({route: `/TaskDetails/4/${this.taskid}`, id: "search-history"});
            this.browserValue2 = [];
            params = {...params, name: this.searchValue1, reftype: "doc"}
            this.TaskRelativeDocList.clearData();
            API.getTaskReferenceList(params).then(action(res => {
                const {isright} = res;
                if (isright && isright === true) {
                    this.prjid = res["prjid"];
                    this.rightMenus = res.rightMenus || {};
                    this.TaskRelativeDocList.getData({dataKey: res.datas});
                } else {
                    this.hasRight = false
                }
            }))
        }
    }
    @action
    changeStateTo = (state) => {
        Toast.loading("Loading...", 10000);
        this.Toasting = true;
        const params = {
            prjid: this.prjid,
            method: state
        };
        API.doPrjPlanOperation(params).then(action(res => {
            Toast.hide()
            this.Toasting = false;
            if (res.success) {
                Bubble.success(getLabel("83923", "提交成功！"), 1);
                this.init(this.tabIndex, this.prjid, this.viewtype);
            } else {
                Bubble.error(res.msg, 1);
            }
        }))
    }

    @action
    deleteCard = () => {
        const params = {
            method: "delete",
            taskid: this.taskid
        }
        Modal.alert(getLabel("15172", "系统提示"), getLabel("83925", "该任务及其子任务都会被删除，您确认要删除吗？"), [
            {text: getLabel("31129", "取消")},
            {
                text: getLabel("826", "确定"), onPress: () => {
                    Toast.loading("Loading...", 10000);
                    this.Toasting = true;
                    API.doTaskOperation(params).then(action(res => {
                        Toast.hide()
                        this.Toasting = false;
                        if (res.success) {
                            Bubble.success(getLabel("83472", "删除成功！"), 1);
                            this.history.go(-1);
                            this.init(this.tabIndex, this.parentid);
                        } else {
                            Bubble.error(res.msg, 1);
                        }
                    }))
                }
            },
        ])
    }

    @action
    addRelativeFile = (id, type, history) => {
        Toast.loading("Loading...", 10000);
        this.Toasting = true;
        let params = {
            dotype: type,
            method: "add",
            prjid: this.prjid,
            taskid: this.taskid,
        }
        if (type === "workflow") {
            params = {...params, requestid: id}
        } else if (type === "doc") {
            params = {...params, docid: id}
        }
        API.doTaskReference(params).then(action(res => {
            Toast.hide()
            this.Toasting = false;
            if (res.success) {
                Bubble.success(getLabel("387620", "新增成功！"), 1)
                this.init(this.tabIndex, this.taskid);
                if (type === "workflow") {
                    history.replace(`/TaskDetails/3/${this.taskid}`)
                } else if (type === "doc") {
                    history.replace(`/TaskDetails/4/${this.taskid}`)
                }
            } else {
                Bubble.error(getLabel("500541", "操作异常，请联系管理员！"), 1)
            }
        }))
    }
    @action
    deleteRelativeFile = (id, type) => {
        Modal.alert(getLabel("15172", "系统提示"), getLabel("15097", "确定要删除吗？"), [
            {text: getLabel("31129", "取消")},
            {
                text: getLabel("826", "确定"), onPress: () => {
                    Toast.loading("Loading...", 10000);
                    this.Toasting = true;
                    let params = {
                        dotype: type,
                        method: "del",
                        ids: id
                    }
                    API.doTaskReference(params).then(action(res => {
                        Toast.hide();
                        this.Toasting = false;
                        if (res.success) {
                            Bubble.success(getLabel("83472", "删除成功！"), 1)
                            this.init(this.tabIndex, this.taskid);
                        } else {
                            Bubble.error(getLabel("500541", "操作异常，请联系管理员！"), 1)
                        }
                    }))
                }
            }])
    }

    @action
    linkToAccessory = (url) => {
        if (url) {
            try {
                window.em.openLink({
                    url: url, // 要打开链接的地址
                    openType: 2, // 打开方式 1:当前窗口 2:新窗口 3:系统默认浏览器
                    sysId: window.localStorage.emobile_ec_id    // 集成系统ID
                });
            } catch (e) {
            }
        }
    }
}
